package org.compression.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Writer;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.compression.mapper.AudioContentMapper;
import org.compression.mapper.GetNamesMapper;
import org.compression.services.FileService;
import org.compression.services.imp.AduioAttrServiceImp;
import org.compression.services.imp.FileServiceImp;
import org.compression.services.imp.GetNames;
import org.compression.services.imp.SerivceContrastImp;
import org.compression.util.RedisTestStream;
import org.compression.util.RedisUtil;
import org.compression.util.SearchTxtServiceUtil;
import org.model.Condition;
import org.model.Member;
import org.model.SearchModel;
import org.model.TNewMagazine;
import org.model.business.FiledownModel;
import org.model.business.Magazine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;



@RestController
@RequestMapping("file")
public class FileController {


	private Logger logger = LoggerFactory.getLogger(FileController.class);

	@Value("${file.path}")
	public String filepath;

	@Value("${file.pathImage}")
	public String pathImage;




	@Autowired
	FileService mFileServiceImp;


	@Autowired
	GetNames mGetNames;

	@Autowired
	RedisUtil	mRedisUtil;


	RedisTestStream os = new RedisTestStream();
	
	
	@RequestMapping(value ="/uploadFile/{id}", method = RequestMethod.POST,headers = "content-type=multipart/form-data")
	public Object uploadFile(MultipartHttpServletRequest request,
			@RequestParam(value = "file", required = true) MultipartFile file,@PathVariable String id) throws Exception {
		return	mFileServiceImp.writeFilePath(request, file,id);
	}

	@RequestMapping(value ="/uploadCover/{id}", method = RequestMethod.POST,headers = "content-type=multipart/form-data")
	public Object uploadCover(MultipartHttpServletRequest request,
			@RequestParam(value = "file", required = true) MultipartFile file,@PathVariable String id) throws Exception {
		return	mFileServiceImp.uploadCover(request, file,id);
	}




	@RequestMapping(value ="/downloadfile", method = RequestMethod.POST)
	public Object downloadfile() {
		return mGetNames.getMagazine();
	}


	@RequestMapping(value ="/tablesName", method = RequestMethod.POST)
	public Object listTables() {
		return mGetNames.getAllNames();
	}


	@Autowired
	SerivceContrastImp mSerivceContrastImp;

	@RequestMapping(value ="/contrast", method = RequestMethod.POST)
	public Object Contrast(@RequestBody String str) {
		return mSerivceContrastImp.getList(str);
	}



	// mFileServiceImp.transformation(model);
	@Autowired
	SearchTxtServiceUtil 	mSearchTxtServiceUtil;
	@RequestMapping(value ="/search", method = RequestMethod.POST)
	public void searchString(@RequestBody SearchModel model) throws Exception {
		mSearchTxtServiceUtil.tss();
	}

	@RequestMapping(value ="/filedowndImage/{memberId}/{magazineId}", method = RequestMethod.GET)
	public void filedowndImage(HttpServletResponse response,@PathVariable("memberId") String memberId,@PathVariable("magazineId") String magazineId) throws IOException {
		mFileServiceImp.filedowndImage(response,memberId,magazineId);
	} 


	@RequestMapping(value ="/filedowndpdf/{memberId}/{magazineId}", method = RequestMethod.GET)
	public void filedowndpdf(HttpServletResponse response,@PathVariable("memberId") String memberId,@PathVariable("magazineId") String magazineId) throws IOException {
		mFileServiceImp.filedowndpdf(response,memberId,magazineId);
	} 


	@Autowired
	AudioContentMapper mAudioContentMapper;

	
	
	//谋篇音频下载
	@RequestMapping(value ="/filedowndAudio/{periodId}/{page}", method = RequestMethod.GET)
	public  synchronized void filedowndAudio(HttpServletResponse response,@PathVariable("periodId") String periodId,@PathVariable("page") String page) throws IOException {
		List<String> path;
		if((path=(List<String>) mRedisUtil.get(getkeys(this.getClass(),periodId,page)))!=null) {
		}else {
			path= mAudioContentMapper.selectPath(page,periodId);
			mRedisUtil.set(getkeys(this.getClass(),periodId,page), path);
		}
		File pdfFile;
		if(os.getFile("test")==null) {
			pdfFile = new File(path.get(0));
			os.setFile("test",path.get(0));
		}else {
			 pdfFile =os.getFile("test");
		}
		logger.info(pdfFile.getName()+"");
		if (!pdfFile.exists()) {
			response.setContentType("text/html; charset=utf8");
			response.getWriter().println("无权限");
			return;
		}
		response.setHeader("content-type", "application/octet-stream");
		response.setContentType("application/octet-stream");
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Content-Disposition", "attachment;filename="+ new String(pdfFile.getName().getBytes("UTF-8"),"iso-8859-1")+"");
		byte[] buff = new byte[(int) (pdfFile.length())];
		BufferedInputStream bis = null;
		OutputStream os = null;
		try {
			os = response.getOutputStream();
			bis = new BufferedInputStream(new FileInputStream(pdfFile));
			System.out.println(buff.length);
			int	i = bis.read(buff);
			while (i != -1) {
				os.write(buff, 0, buff.length);
				os.flush();
				System.out.println(i);
				i = bis.read(buff);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (bis != null) {
				try {
					bis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}   
	} 
	
	@Autowired
	AduioAttrServiceImp mAduioAttrServiceImp;
	
	//谋篇封面下载
	@RequestMapping(value ="/filedowndAudioCover/{periodId}/", method = RequestMethod.GET)
	public void filedowndAudioCover(HttpServletResponse response,@PathVariable("periodId") String periodId) throws IOException {
		List<String> path;
		if((path=(List<String>) mRedisUtil.get(getkeys(this.getClass(),periodId)))!=null) {
		}else {
			path= mAduioAttrServiceImp.selectPath(periodId);
			mRedisUtil.set(getkeys(this.getClass(),periodId), path);
		}
		File pdfFile = new File(path.get(0));
		logger.info(pdfFile.getName()+"");
		if (!pdfFile.exists()) {
			response.setContentType("text/html; charset=utf8");
			response.getWriter().println("无权限");
			return;
		}
		response.setHeader("content-type", "application/octet-stream");
		response.setContentType("application/octet-stream");
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Content-Disposition", "attachment;filename="+ new String(pdfFile.getName().getBytes("UTF-8"),"iso-8859-1")+"");
		byte[] buff = new byte[(int) (pdfFile.length())];
		BufferedInputStream bis = null;
		OutputStream os = null;
		try {
			os = response.getOutputStream();
			bis = new BufferedInputStream(new FileInputStream(pdfFile));
			System.out.println(buff.length);
			int	i = bis.read(buff);
			while (i != -1) {
				os.write(buff, 0, buff.length);
				os.flush();
				System.out.println(i);
				i = bis.read(buff);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (bis != null) {
				try {
					bis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}   
	} 
	
	
	


	public String getkeys(Class mClass,Object ... objects) {
		String args=mClass.getName()+"."+mClass.getMethods()[9].getName()+":";
		for(Object object:objects) {
			args+=object+",";
		}
		args=args.substring(0, args.length()-2);
		return args;
	}






}
